import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';
import { GetMatterDetail, EditMatterUserList } from '@/services/official-doc';
import { MatterItemDetail, EDIT_TYPE } from '@/pages/official-doc/interface.d';
import FormGroup, { FormListItem } from '@/components/form-group';
import Tabs from '@/components/antd-tabs';
import StandardCard from '@/pages/official-doc/components/standard-card';
import Empty from '@/components/empty/index';
import Avatar from '@/components/avatar';
import ContractSelectModal from '@/components/ContractSelectModal';
import ButtonFooter from '@/components/button-footer';
import { SwipeAction, Toast } from 'antd-mobile-v2';
import { SecondConfirm } from '@/components/second-confirm';
import { useDispatch, useSelector } from 'react-redux';
import classnames from 'classnames';
import { getSearchName } from '@/utils/index';
import { MENU_TYPE } from '@/pages/official-doc/components/matter-list';

const tabs = [
  { title: '发放标准', key: 'standardList' },
  { title: '可查阅人员', key: 'lookUpUserList' }
];

const MatterDetail: React.FC<RouterProps> = (props) => {
  const formRef = useRef();
  const id = useRef(props.match.params.id);
  const [detail, setDetail] = useState<MatterItemDetail>();
  const [formData, setFormData] = useState<FormListItem[]>([]);
  const [curTabContent, setCurTabContent] = useState<JSX.Element>();
  const [activeTab, setActiveTab] = useState<string>();
  const [selecterVisible, setSelecterVisible] = useState<boolean>(false);
  const [resetData, setResetData] = useState<any[]>([]);
  const dispatch = useDispatch();
  const { orgTree } = useSelector((state: any) => ({
    orgTree: state.common.orgTree
  }));
  const [type] = useState(Number(getSearchName('type')));

  useEffect(() => {
    formatData();
    handleSetCurTabContent();
    setResetData(formatFormList(detail?.lookUpUserList));
  }, [detail]);

  useEffect(() => {
    handleSetCurTabContent();
  }, [activeTab]);

  useEffect(() => {
    dispatch({ type: 'common/getOrgTreeDataSaga' });
    getDetail();
  }, []);

  const handleSetCurTabContent = () => {
    if (activeTab === 'standardList') {
      return setCurTabContent(standardListDom());
    } else if (activeTab === 'lookUpUserList') {
      return setCurTabContent(lookUpUserListDom());
    }
    setCurTabContent(standardListDom());
  };

  const handleTabsChange = (tab: any) => {
    setActiveTab(tab.key);
  };

  const standardListDom = () => {
    return (
      <div className={styles.standardList}>
        {detail?.standardDetailResList?.length ? (
          detail.standardDetailResList?.map((item) => (
            <StandardCard data={item} key={item.id} />
          ))
        ) : (
          <Empty text="暂无" />
        )}
      </div>
    );
  };

  const canEdit = () => {
    return (
      detail?.isEdit === EDIT_TYPE.ENABLE && type !== MENU_TYPE.MY_AUTHORZED
    );
  };

  const lookUpUserListDom = () => {
    return (
      <div className={styles.lookUpUserList}>
        {detail?.lookUpUserList?.length ? (
          detail?.lookUpUserList.map((item) => (
            <SwipeAction
              key={item.id}
              // style={{ backgroundColor: 'gray' }}
              autoClose
              disabled={canEdit() ? false : true}
              right={[
                {
                  text: '删除',
                  onPress: () => handleDeleteMember(item),
                  style: {
                    backgroundColor: '#F4333C',
                    color: 'white',
                    padding: '0 4px',
                    fontSize: '16px'
                  }
                }
              ]}
            >
              <div className={styles.lookUpUserListItem}>
                <div className={styles.avatar}>
                  <Avatar name={item.name} />
                </div>
                <div className={styles.info}>
                  <span className={styles.name}>{item.name}</span>
                  <span className={styles.orgName}>{item.orgName}</span>
                </div>
              </div>
            </SwipeAction>
          ))
        ) : (
          <Empty text="暂无" />
        )}
      </div>
    );
  };

  const getDetail = async () => {
    const res = await GetMatterDetail(id.current);
    res.data && setDetail(res.data);
  };

  const formatFormList = (list: any[]) => {
    if (!list) return [];
    return list.map((item: any) => ({
      text: item.name,
      type: item.userOrgType,
      value: item.id
    }));
  };

  const formatRequestList = (list: any[]) => {
    if (!list) return [];
    console.log(list);
    return list.map((item: any) => ({
      name: item.title,
      userOrgType: item.type,
      id: item.key,
      orgName: item.parentName
    }));
  };
  const matterTotalText =
    detail?.matterTotal === -1 ? '不限额' : `${detail?.matterTotal}元` || '无';
  console.log('detail--------------{}', detail);

  const formatData = () => {
    const result = [
      {
        label: '经办人',
        valueKey: 'managerName',
        type: 'text',
        content: detail?.managerName || '无'
      },
      {
        label: '事项总额',
        valueKey: 'matterTotal',
        type: 'text',
        content: matterTotalText
      },
      {
        label: '备注',
        valueKey: 'remark',
        type: 'text',
        content: detail?.remark || '无'
      }
    ];
    setFormData(result);
  };

  const openModal = () => {
    setSelecterVisible(true);
  };

  const closeModal = () => {
    setSelecterVisible(false);
  };

  const onSubmit = async (_isHandle: boolean, value: any[]) => {
    // 调用修改人员接口
    const data = {
      id: id.current,
      lookUpUserList: formatRequestList(value)
    };
    const res = await EditMatterUserList(data);
    setSelecterVisible(false);
    if (res.status === 200) {
      Toast.info('编辑成功');
      getDetail();
    }
  };

  const handleDeleteMember = (member) => {
    SecondConfirm({
      buttons: [
        {
          text: '删除',
          cb: async () => {
            const list = detail.lookUpUserList.filter(
              (item: any) => item.id !== member.id
            );
            const data = {
              id: id.current,
              lookUpUserList: list
            };
            const res = await EditMatterUserList(data);
            if (res.status === 200) {
              Toast.info('删除成功');
              getDetail();
            }
          }
        },
        {
          text: '取消'
        }
      ],
      message: `确认删除${member.name}？`
    });
  };

  const getButtonOptions = () => [
    {
      text: '+ 添加人员',
      onClick: openModal
    }
  ];

  return (
    <div className={styles.wrap}>
      {detail && (
        <React.Fragment>
          <div className={styles.title}>
            <p className={styles.titleText}>{detail.matterName}</p>
          </div>
          <div className={styles.formWrap}>
            <FormGroup ref={formRef} formList={formData} />
          </div>
          <div
            className={classnames(
              styles.standardContent,
              activeTab === 'lookUpUserList' &&
                detail?.isEdit === EDIT_TYPE.ENABLE
                ? styles.withMargin
                : ''
            )}
          >
            <Tabs
              tabs={tabs}
              initialPage={0}
              leftTabs
              animated={false}
              swipeable={false}
              useOnPan={false}
              onChange={handleTabsChange}
            >
              <div>{curTabContent}</div>
            </Tabs>
          </div>
          {activeTab === 'lookUpUserList' && canEdit() && (
            <ButtonFooter data={getButtonOptions()} />
          )}
          <ContractSelectModal
            modalStatus={selecterVisible}
            closeModal={closeModal}
            submit={onSubmit}
            resetData={resetData} // 表单回填的数据，使用时参考公文录入功能的表单回填写法
            type="all"
            mode="multiple"
            orgData={orgTree}
            saveOnSubmit
          />
        </React.Fragment>
      )}
    </div>
  );
};

export default MatterDetail;
